"use client"

import type React from "react"
import { useState, useRef } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Animated, Platform, Dimensions } from "react-native"
import { Volume2, CheckCircle2, XCircle, HelpCircle } from "lucide-react-native"
import { theme } from "../../constants/theme"

// 获取屏幕尺寸
const { width } = Dimensions.get("window")
const isTablet = width > 768

interface Option {
    id: string
    text: string
    correct: boolean
}

interface ChoiceCardProps {
    word: string
    phonetic: string
    options: Option[]
    isPlaying?: boolean
    onPlayAudio?: () => void
    onOptionSelect?: (optionId: string, isCorrect: boolean) => void
    onCorrectAnswer?: () => void
}

export const ChoiceCard: React.FC<ChoiceCardProps> = ({
    word,
    phonetic,
    options,
    isPlaying = false,
    onPlayAudio,
    onOptionSelect,
    onCorrectAnswer,
}) => {
    const [selectedOption, setSelectedOption] = useState<string | null>(null)
    const [isCorrect, setIsCorrect] = useState<boolean | null>(null)
    const [showFeedback, setShowFeedback] = useState(false)

    // 动画值
    const correctAnim = useRef(new Animated.Value(1)).current
    const pulseAnim = useRef(new Animated.Value(1)).current
    const feedbackAnim = useRef(new Animated.Value(0)).current

    // 处理选项选择
    const handleOptionSelect = (optionId: string) => {
        if (selectedOption !== null) return // 已经选择了选项，不允许再次选择

        const option = options.find((opt) => opt.id === optionId)
        if (!option) return

        setSelectedOption(optionId)
        setIsCorrect(option.correct)
        setShowFeedback(true)

        // 通知父组件
        if (onOptionSelect) {
            onOptionSelect(optionId, option.correct)
        }

        if (option.correct) {
            // 播放正确动画
            Animated.sequence([
                Animated.timing(correctAnim, {
                    toValue: 1.2,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(correctAnim, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start()

            // 脉冲动画
            Animated.loop(
                Animated.sequence([
                    Animated.timing(pulseAnim, {
                        toValue: 1.05,
                        duration: 500,
                        useNativeDriver: true,
                    }),
                    Animated.timing(pulseAnim, {
                        toValue: 1,
                        duration: 500,
                        useNativeDriver: true,
                    }),
                ]),
                { iterations: 3 },
            ).start()

            // 延迟后通知父组件正确答案
            setTimeout(() => {
                if (onCorrectAnswer) {
                    onCorrectAnswer()
                }
                // 重置状态
                setSelectedOption(null)
                setIsCorrect(null)
                setShowFeedback(false)
            }, 1500)
        } else {
            // 显示错误反馈，然后自动消失
            Animated.sequence([
                Animated.timing(feedbackAnim, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.delay(1500),
                Animated.timing(feedbackAnim, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }),
            ]).start(() => {
                setShowFeedback(false)
                setSelectedOption(null)
                setIsCorrect(null)
            })
        }
    }

    // 获取选项样式
    const getOptionStyle = (optionId: string) => {
        if (selectedOption === optionId) {
            if (isCorrect) {
                return [styles.option, styles.optionCorrect]
            } else {
                return [styles.option, styles.optionWrong]
            }
        }
        return [styles.option]
    }

    // 获取选项文本样式
    const getOptionTextStyle = (optionId: string) => {
        if (selectedOption === optionId) {
            if (isCorrect) {
                return [styles.optionText, styles.optionTextCorrect]
            } else {
                return [styles.optionText, styles.optionTextWrong]
            }
        }
        return [styles.optionText]
    }

    return (
        <View style={styles.card}>
            <View style={styles.wordContainer}>
                <Text style={styles.word}>{word}</Text>
                <TouchableOpacity style={styles.soundButton} onPress={onPlayAudio} disabled={isPlaying} activeOpacity={0.7}>
                    <Volume2 size={24} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>
            <Text style={styles.phonetic}>{phonetic}</Text>

            {/* 选项 */}
            <View style={styles.optionsContainer}>
                {options.map((option) => (
                    <TouchableOpacity
                        key={option.id}
                        style={getOptionStyle(option.id)}
                        onPress={() => handleOptionSelect(option.id)}
                        disabled={selectedOption !== null}
                        activeOpacity={0.8}
                    >
                        <Text style={getOptionTextStyle(option.id)}>{option.text}</Text>
                        {selectedOption === option.id && isCorrect && (
                            <Animated.View
                                style={{
                                    transform: [{ scale: correctAnim }],
                                }}
                            >
                                <CheckCircle2 size={20} color={theme.colors.secondary.green.default} />
                            </Animated.View>
                        )}
                        {selectedOption === option.id && !isCorrect && (
                            <XCircle size={20} color={theme.colors.secondary.red.default} />
                        )}
                    </TouchableOpacity>
                ))}
            </View>

            {/* 提示和反馈 */}
            <View style={styles.feedbackArea}>
                {!showFeedback && (
                    <View style={styles.hintContainer}>
                        <HelpCircle size={16} color={theme.colors.neutral.gray} />
                        <Text style={styles.hintText}>选择与单词对应的中文意思</Text>
                    </View>
                )}

                {showFeedback && !isCorrect && (
                    <Animated.View
                        style={[
                            styles.feedbackContainer,
                            styles.feedbackWrong,
                            {
                                opacity: feedbackAnim,
                                transform: [
                                    {
                                        translateY: feedbackAnim.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: [10, 0],
                                        }),
                                    },
                                ],
                            },
                        ]}
                    >
                        <XCircle size={16} color={theme.colors.secondary.red.default} />
                        <Text style={[styles.feedbackText, styles.feedbackTextWrong]}>回答错误！</Text>
                    </Animated.View>
                )}

                {showFeedback && isCorrect && (
                    <Animated.View
                        style={[
                            styles.feedbackContainer,
                            styles.feedbackCorrect,
                            {
                                transform: [{ scale: pulseAnim }],
                            },
                        ]}
                    >
                        <CheckCircle2 size={16} color={theme.colors.secondary.green.default} />
                        <Text style={[styles.feedbackText, styles.feedbackTextCorrect]}>答对了！</Text>
                    </Animated.View>
                )}
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    card: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    wordContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.sm,
    },
    word: {
        fontSize: isTablet ? 48 : 36,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        textAlign: "center",
    },
    soundButton: {
        marginLeft: theme.spacing.md,
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginBottom: theme.spacing.xl,
    },
    optionsContainer: {
        flex: 1,
        justifyContent: "center",
        gap: theme.spacing.lg,
    },
    option: {
        backgroundColor: "rgba(91, 142, 244, 0.05)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderWidth: 2,
        borderColor: "transparent",
        minHeight: 60, // 固定高度，避免选择后布局变化
    },
    optionCorrect: {
        borderColor: theme.colors.secondary.green.default,
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    optionWrong: {
        borderColor: theme.colors.secondary.red.default,
        backgroundColor: "rgba(255, 59, 48, 0.1)",
    },
    optionText: {
        fontSize: isTablet ? theme.fontSize.lg : theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    optionTextCorrect: {
        color: theme.colors.secondary.green.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    optionTextWrong: {
        color: theme.colors.secondary.red.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    feedbackArea: {
        height: 40, // 固定高度，避免反馈显示时布局变化
        justifyContent: "center",
        alignItems: "center",
        marginTop: theme.spacing.lg,
    },
    hintContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        gap: theme.spacing.xs,
    },
    hintText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
    },
    feedbackContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        gap: theme.spacing.xs,
    },
    feedbackCorrect: {
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    feedbackWrong: {
        backgroundColor: "rgba(255, 59, 48, 0.1)",
    },
    feedbackText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
    feedbackTextCorrect: {
        color: theme.colors.secondary.green.default,
    },
    feedbackTextWrong: {
        color: theme.colors.secondary.red.default,
    },
})

